<?php
declare (strict_types = 1);

namespace app\controller\organization;

use app\BaseController;
use app\model\Organization as TeamModel;
use app\model\OrganizationMembers;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\Response;
use utils\HashID;

class Index extends BaseController
{
    /**
     * 查询团队列表
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): Response
    {
        $userId = $this->request->get('user_id');
        
        if (!$userId) {
            return apiResponse(400, '缺少用户ID参数');
        }
        
        // 使用模型查询用户关联的团队信息列表，并获取用户在该团队中的角色
        $teams = OrganizationMembers::with(['organization', 'role'])
            ->where('user_id', $userId)
            ->order('join_at', 'desc')
            ->select()
            ->map(function($item) {
                return [
                    'id' => $item->organization->id ?? null,
                    'name' => $item->organization->name ?? null,
                    'avatar' => $item->organization->avatar ?? null,
                    'description' => $item->organization->description ?? null,
                    'role_id'=> $item->role->id ?? null,
                    'role_name' => $item->role->name ?? null,
                    'role_slug'=> $item->role->slug ?? null,
                    'join_time' => $item->join_at,
                    'role_color'=> $item->role->color ?? null,
                    'permissions'=> $item->role->permissions ?? [],
                    'create_time'=> $item->organization->create_time,
                    'status'=> $item->organization->status
                ];
            })
            ->toArray();
        return apiResponse(200, 'success', $teams);
    }


    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        $param = $request->post();
        // 验证必要参数
        if (empty($param['name']) || empty($param['user_id'])) {
            return apiResponse(400, '团队名称和用户ID不能为空');
        }
        // 获取当前用户ID
        $userId = $param['user_id'];
        try {
            //查询当前用户是否存在创建上限
            $teamLimit = TeamModel::where('user_id', $userId)->count();
            if ($teamLimit >= config('organization.create')) {
                return apiResponse(400, '当前用户已创建团队数量达到上限');
            }
            // 创建团队
            $teamId = HashID::generate();
            while (TeamModel::where('id', $teamId)->find()){
                $teamId = HashID::generate();
            }
            //检查同用户下是否存在相同名字的 团队
            $team = TeamModel::where('name', $param['name'])->where('user_id', $userId)->count();
            if ($team > 0) {
                return apiResponse(400, '用户下已存在同名团队');
            }
            // 保存团队数据
            TeamModel::create([
                'id' => $teamId,
                'name' => $param['name'],
                'description' => $param['description'] ?? '',
                'user_id' => $userId,
                'status' => 1
            ]);
            //写入团队成员表 默认角色为管理员
            OrganizationMembers::create([
                'oid' => $teamId,
                'user_id' => $userId,
                'role_id' => 1,
                'status' => 1
            ]);
            return apiResponse(200, '团队创建成功');
        } catch (\Exception $e) {
            return apiResponse(500, '团队创建失败: ' . $e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id): Response
    {
        return apiResponse(200, 'success');
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return Response
     */
    public function delete($id)
    {
        return apiResponse(200, 'success');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return Response
     */
    public function read($id)
    {
        return apiResponse(200, 'success');
    }

    public function grade_capacity()
    {
        $id = $this->request->param('oid');
        if (!$id){
            return apiResponse(400, '缺少团队ID参数');
        }
        $grade = TeamModel::where('id', $id)->value('grade');
        $config = config('organization.grade');
    }
}